<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { statisticsDB } from '@/utils/database'
import type { Overview, CategoryStats } from '@/types'
import { CATEGORY_ICONS } from '@/types'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import { Line, Doughnut } from 'vue-chartjs'

dayjs.extend(isoWeek)
dayjs.extend(weekOfYear)

// 注册Chart.js组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  ArcElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

const router = useRouter()

// 数据状态
const loading = ref(false)
const overview = ref<Overview | null>(null)
const categoryStats = ref<CategoryStats[]>([])
const dailyStats = ref<any[]>([])

// 时间筛选
const reportType = ref<'week' | 'month' | 'year' | 'custom'>('month')
const currentDate = ref(dayjs())
const customDateRange = ref<[Date, Date] | null>(null)
const showCalendarPicker = ref(false)

// 支出/收入类型
const activeType = ref<'expense' | 'income'>('expense')

// 上个周期数据
const lastPeriodOverview = ref<Overview | null>(null)

onMounted(async () => {
  await loadData()
})

// 计算日期范围（周一作为一周开始）
const dateRange = computed(() => {
  const now = currentDate.value
  
  switch (reportType.value) {
    case 'week':
      // 设置周一为一周开始（isoWeek）
      const weekStart = now.startOf('isoWeek')
      const weekEnd = now.endOf('isoWeek')
      const weekNum = now.isoWeek()
      return {
        startDate: weekStart.format('YYYY-MM-DD'),
        endDate: weekEnd.format('YYYY-MM-DD'),
        label: `第${weekNum}周 (${weekStart.format('MM/DD')}-${weekEnd.format('MM/DD')})`
      }
    case 'month':
      return {
        startDate: now.startOf('month').format('YYYY-MM-DD'),
        endDate: now.endOf('month').format('YYYY-MM-DD'),
        label: now.format('YYYY年MM月')
      }
    case 'year':
      return {
        startDate: now.startOf('year').format('YYYY-MM-DD'),
        endDate: now.endOf('year').format('YYYY-MM-DD'),
        label: now.format('YYYY年')
      }
    case 'custom':
      if (customDateRange.value) {
        return {
          startDate: dayjs(customDateRange.value[0]).format('YYYY-MM-DD'),
          endDate: dayjs(customDateRange.value[1]).format('YYYY-MM-DD'),
          label: `${dayjs(customDateRange.value[0]).format('YYYY/MM/DD')}-${dayjs(customDateRange.value[1]).format('MM/DD')}`
        }
      }
      return {
        startDate: now.startOf('month').format('YYYY-MM-DD'),
        endDate: now.endOf('month').format('YYYY-MM-DD'),
        label: '自定义'
      }
  }
})

// 上个周期的日期范围
const lastPeriodRange = computed(() => {
  switch (reportType.value) {
    case 'week':
      return {
        startDate: currentDate.value.subtract(1, 'week').startOf('isoWeek').format('YYYY-MM-DD'),
        endDate: currentDate.value.subtract(1, 'week').endOf('isoWeek').format('YYYY-MM-DD')
      }
    case 'month':
      return {
        startDate: currentDate.value.subtract(1, 'month').startOf('month').format('YYYY-MM-DD'),
        endDate: currentDate.value.subtract(1, 'month').endOf('month').format('YYYY-MM-DD')
      }
    case 'year':
      return {
        startDate: currentDate.value.subtract(1, 'year').startOf('year').format('YYYY-MM-DD'),
        endDate: currentDate.value.subtract(1, 'year').endOf('year').format('YYYY-MM-DD')
      }
    default:
      return null
  }
})

const loadData = async () => {
  try {
    loading.value = true
    
    const { startDate, endDate, label } = dateRange.value
    console.log(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`)
    console.log(`📊 加载${reportType.value}报表数据:`, label)
    console.log(`📅 查询日期范围: ${startDate} 到 ${endDate}`)
    
    // 并行请求所有数据
    const [overviewRes, categoryRes, dailyRes] = await Promise.all([
      statisticsDB.getOverview({ startDate, endDate }),
      statisticsDB.getCategories({ startDate, endDate }),
      statisticsDB.getDaily({ startDate, endDate })
    ])
    
    console.log(`📊 查询结果 - 概览:`, overviewRes)
    console.log(`📊 查询结果 - 分类统计:`, categoryRes)
    console.log(`📊 查询结果 - 每日统计:`, dailyRes)

    if (overviewRes && (overviewRes as any).status === 'success') {
      overview.value = (overviewRes as any).data
      console.log(`✅ 概览数据加载完成 - 收入:${overview.value?.totalIncome}, 支出:${overview.value?.totalExpense}`)
    } else {
      console.warn('⚠️ 概览数据加载失败或无数据')
    }

    if (categoryRes && (categoryRes as any).status === 'success') {
      categoryStats.value = (categoryRes as any).data.categoryStats || []
      console.log(`✅ 分类统计加载完成 - 共${categoryStats.value.length}个分类`)
    } else {
      console.warn('⚠️ 分类统计加载失败或无数据')
    }

    if (dailyRes && (dailyRes as any).status === 'success') {
      dailyStats.value = (dailyRes as any).data.dailyStats || []
      console.log(`✅ 每日统计加载完成 - 共${dailyStats.value.length}天有数据`)
      if (dailyStats.value.length > 0) {
        console.log(`📅 数据日期范围: ${dailyStats.value[0].date} 到 ${dailyStats.value[dailyStats.value.length-1].date}`)
      }
    } else {
      console.warn('⚠️ 每日统计加载失败或无数据')
    }

    // 加载上个周期数据
    if (lastPeriodRange.value) {
      const lastRes = await statisticsDB.getOverview(lastPeriodRange.value)
      if (lastRes && (lastRes as any).status === 'success') {
        lastPeriodOverview.value = (lastRes as any).data
      }
    }
    console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`)
  } catch (error) {
    console.error('❌ 加载统计数据失败:', error)
    showToast('加载失败')
  } finally {
    loading.value = false
  }
}

// 监听报表类型和日期变化
watch([reportType, currentDate, customDateRange], () => {
  loadData()
})

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 切换报表类型
const changeReportType = (type: typeof reportType.value) => {
  reportType.value = type
  currentDate.value = dayjs()
  console.log(`📊 切换到${type}报表，当前日期:`, currentDate.value.format('YYYY-MM-DD'))
  if (type === 'week') {
    const weekStart = currentDate.value.startOf('isoWeek').format('YYYY-MM-DD')
    const weekEnd = currentDate.value.endOf('isoWeek').format('YYYY-MM-DD')
    console.log(`📅 本周范围: ${weekStart} 到 ${weekEnd}`)
  }
}

// 上一周期
const prevPeriod = () => {
  switch (reportType.value) {
    case 'week':
      currentDate.value = currentDate.value.subtract(1, 'week')
      break
    case 'month':
      currentDate.value = currentDate.value.subtract(1, 'month')
      break
    case 'year':
      currentDate.value = currentDate.value.subtract(1, 'year')
      break
  }
}

// 下一周期
const nextPeriod = () => {
  if (reportType.value === 'custom') return
  
  let next = dayjs()
  switch (reportType.value) {
    case 'week':
      next = currentDate.value.add(1, 'week')
      break
    case 'month':
      next = currentDate.value.add(1, 'month')
      break
    case 'year':
      next = currentDate.value.add(1, 'year')
      break
  }
  
  if (next.isAfter(dayjs(), reportType.value)) {
    showToast('不能查看未来数据')
    return
  }
  
  currentDate.value = next
}

// 自定义日期选择
const showCustomDatePicker = ref(false)
const customStartDate = ref('')
const customEndDate = ref('')
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

const onCustomDateSelect = () => {
  reportType.value = 'custom'
  showCustomDatePicker.value = true
  
  // 设置默认值为当前范围
  if (customDateRange.value) {
    customStartDate.value = dayjs(customDateRange.value[0]).format('YYYY-MM-DD')
    customEndDate.value = dayjs(customDateRange.value[1]).format('YYYY-MM-DD')
  } else {
    const now = dayjs()
    customStartDate.value = now.startOf('month').format('YYYY-MM-DD')
    customEndDate.value = now.format('YYYY-MM-DD')
  }
}

// 快捷选择
const quickSelectDate = (type: 'all' | 'year' | 'month' | 'week') => {
  const now = dayjs()
  switch (type) {
    case 'all':
      customStartDate.value = '2020-01-01'
      customEndDate.value = now.format('YYYY-MM-DD')
      break
    case 'year':
      customStartDate.value = now.subtract(1, 'year').format('YYYY-MM-DD')
      customEndDate.value = now.format('YYYY-MM-DD')
      break
    case 'month':
      customStartDate.value = now.subtract(30, 'day').format('YYYY-MM-DD')
      customEndDate.value = now.format('YYYY-MM-DD')
      break
    case 'week':
      customStartDate.value = now.subtract(7, 'day').format('YYYY-MM-DD')
      customEndDate.value = now.format('YYYY-MM-DD')
      break
  }
  
  // 自动确认选择
  console.log(`📅 快捷选择${type}: ${customStartDate.value} 到 ${customEndDate.value}`)
  confirmCustomDate()
}

// 确认自定义日期
const confirmCustomDate = () => {
  if (!customStartDate.value || !customEndDate.value) {
    showToast('请选择日期')
    return
  }
  
  const start = dayjs(customStartDate.value)
  const end = dayjs(customEndDate.value)
  
  if (start.isAfter(end)) {
    showToast('开始日期不能晚于结束日期')
    return
  }
  
  console.log(`📅 确认自定义日期: ${customStartDate.value} 到 ${customEndDate.value}`)
  customDateRange.value = [start.toDate(), end.toDate()]
  showCustomDatePicker.value = false
  console.log(`✅ customDateRange已更新:`, customDateRange.value)
}

// 日期选择器确认
const onStartDateConfirm = ({ selectedValues }: any) => {
  customStartDate.value = selectedValues.join('-')
  showStartDatePicker.value = false
}

const onEndDateConfirm = ({ selectedValues }: any) => {
  customEndDate.value = selectedValues.join('-')
  showEndDatePicker.value = false
}

// 计算日均
const dailyAverage = computed(() => {
  if (!overview.value) return 0
  const days = reportType.value === 'year' ? 365 : dailyStats.value.length || 1
  const total = activeType.value === 'expense' ? overview.value.totalExpense : overview.value.totalIncome
  return total / days
})

// 比上期差额
const periodDiff = computed(() => {
  if (!overview.value || !lastPeriodOverview.value) return 0
  const current = activeType.value === 'expense' ? overview.value.totalExpense : overview.value.totalIncome
  const last = activeType.value === 'expense' ? lastPeriodOverview.value.totalExpense : lastPeriodOverview.value.totalIncome
  return current - last
})

// 当前类型的分类统计
const currentCategoryStats = computed(() => {
  return categoryStats.value
    .filter(item => item.type === activeType.value)
    .sort((a, b) => b.totalAmount - a.totalAmount)
})

// 当前类型的总金额
const currentTotal = computed(() => {
  return currentCategoryStats.value.reduce((sum, item) => sum + item.totalAmount, 0)
})

// 折线图数据（根据报表类型处理不同粒度）
const lineChartData = computed(() => {
  let labels: string[] = []
  let data: number[] = []
  
  if (reportType.value === 'year') {
    // 年报：按月汇总
    const monthlyData = new Array(12).fill(0)
    dailyStats.value.forEach(item => {
      const month = dayjs(item.date).month() // 0-11
      monthlyData[month] += activeType.value === 'expense' ? item.expense : item.income
    })
    labels = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    data = monthlyData
  } else if (reportType.value === 'week') {
    // 周报：显示7天（周一到周日）
    const weekStart = currentDate.value.startOf('isoWeek')
    const weekData: { [key: string]: number } = {}
    
    // 初始化7天
    for (let i = 0; i < 7; i++) {
      const date = weekStart.add(i, 'day').format('YYYY-MM-DD')
      weekData[date] = 0
    }
    
    // 填充实际数据
    dailyStats.value.forEach(item => {
      if (weekData.hasOwnProperty(item.date)) {
        weekData[item.date] = activeType.value === 'expense' ? item.expense : item.income
      }
    })
    
    // 生成标签和数据
    labels = Object.keys(weekData).map(date => dayjs(date).format('ddd'))
    data = Object.values(weekData)
  } else {
    // 月报和自定义：按天显示
    const { startDate, endDate } = dateRange.value
    const start = dayjs(startDate)
    const end = dayjs(endDate)
    const dayCount = end.diff(start, 'day') + 1
    
    const dailyData: { [key: string]: number } = {}
    
    // 初始化所有天
    for (let i = 0; i < dayCount; i++) {
      const date = start.add(i, 'day').format('YYYY-MM-DD')
      dailyData[date] = 0
    }
    
    // 填充实际数据
    dailyStats.value.forEach(item => {
      if (dailyData.hasOwnProperty(item.date)) {
        dailyData[item.date] = activeType.value === 'expense' ? item.expense : item.income
      }
    })
    
    // 生成标签和数据
    if (reportType.value === 'month') {
      labels = Object.keys(dailyData).map(date => dayjs(date).format('D日'))
    } else {
      // 自定义：如果天数少，显示日期，否则显示月/日
      labels = Object.keys(dailyData).map(date => {
        return dayCount <= 10 ? dayjs(date).format('MM/DD') : dayjs(date).format('D')
      })
    }
    data = Object.values(dailyData)
  }

  return {
    labels,
    datasets: [{
      label: activeType.value === 'expense' ? '支出' : '收入',
      data,
      borderColor: activeType.value === 'expense' ? '#FF6384' : '#36A2EB',
      backgroundColor: activeType.value === 'expense' ? 'rgba(255, 99, 132, 0.1)' : 'rgba(54, 162, 235, 0.1)',
      tension: 0.4,
      fill: true,
      pointRadius: 3,
      pointHoverRadius: 6
    }]
  }
})

const lineChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false
    },
    tooltip: {
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      padding: 12,
      titleColor: '#fff',
      bodyColor: '#fff',
      callbacks: {
        label: (context: any) => {
          return `${context.dataset.label}: ¥${formatAmount(context.parsed.y)}`
        }
      }
    }
  },
  scales: {
    y: {
      beginAtZero: true,
      grid: {
        color: '#f0f0f0'
      },
      ticks: {
        callback: (value: any) => {
          return value >= 1000 ? `${(value / 1000).toFixed(1)}k` : value
        }
      }
    },
    x: {
      grid: {
        display: false
      }
    }
  }
}

// 饼图数据
const pieChartData = computed(() => {
  const top8 = currentCategoryStats.value.slice(0, 8)
  const colors = [
    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
    '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF'
  ]

  return {
    labels: top8.map(item => item.categoryName),
    datasets: [{
      data: top8.map(item => item.totalAmount),
      backgroundColor: colors,
      borderWidth: 2,
      borderColor: '#fff'
    }]
  }
})

const pieChartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false
    },
    tooltip: {
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      padding: 12,
      callbacks: {
        label: (context: any) => {
          const label = context.label || ''
          const value = context.parsed
          const percentage = ((value / currentTotal.value) * 100).toFixed(1)
          return `${label}: ¥${formatAmount(value)} (${percentage}%)`
        }
      }
    }
  },
  cutout: '60%'
}

// 跳转到分类明细
const goToCategoryDetail = (category: CategoryStats) => {
  router.push({
    path: '/category-detail',
    query: {
      categoryId: category.categoryId,
      categoryName: category.categoryName,
      startDate: dateRange.value.startDate,
      endDate: dateRange.value.endDate
    }
  })
}
</script>

<template>
  <div class="statistics-view">
    <van-nav-bar title="收支报表" left-arrow @click-left="router.back()" />

    <!-- 报表类型选择 -->
    <div class="report-tabs">
      <div 
        class="tab-item" 
        :class="{ active: reportType === 'week' }"
        @click="changeReportType('week')"
      >
        周报
      </div>
      <div 
        class="tab-item" 
        :class="{ active: reportType === 'month' }"
        @click="changeReportType('month')"
      >
        月报
      </div>
      <div 
        class="tab-item" 
        :class="{ active: reportType === 'year' }"
        @click="changeReportType('year')"
      >
        年报
      </div>
      <div 
        class="tab-item" 
        :class="{ active: reportType === 'custom' }"
        @click="onCustomDateSelect"
      >
        自定义
      </div>
    </div>

    <!-- 时间选择 -->
    <div class="time-selector">
      <van-icon 
        name="arrow-left" 
        @click="prevPeriod" 
        :class="{ disabled: reportType === 'custom' }"
      />
      <span class="time-text">{{ dateRange.label }}</span>
      <van-icon 
        name="arrow" 
        @click="nextPeriod"
        :class="{ disabled: reportType === 'custom' }"
      />
    </div>

    <!-- 支出/收入切换 -->
    <div class="type-tabs">
      <div 
        class="tab-item" 
        :class="{ active: activeType === 'expense' }"
        @click="activeType = 'expense'"
      >
        支出
      </div>
      <div 
        class="tab-item" 
        :class="{ active: activeType === 'income' }"
        @click="activeType = 'income'"
      >
        收入
      </div>
    </div>

        <div v-if="loading" class="loading">
          <van-loading />
        </div>
        
    <div v-else class="content">
      <!-- 数据卡片 -->
      <div v-if="overview" class="stats-cards">
        <div class="card-row">
          <div class="stat-card">
            <div class="label">总{{ activeType === 'expense' ? '支出' : '收入' }}(元)</div>
            <div class="value primary">
              {{ formatAmount(activeType === 'expense' ? overview.totalExpense : overview.totalIncome) }}
            </div>
          </div>
          <div class="stat-card">
            <div class="label">日均{{ activeType === 'expense' ? '支出' : '收入' }}(元)</div>
            <div class="value">{{ formatAmount(dailyAverage) }}</div>
          </div>
              </div>
        <div class="card-row">
          <div class="stat-card">
            <div class="label">比{{ reportType === 'week' ? '上周' : reportType === 'month' ? '上月' : '去年' }}</div>
            <div class="value" :class="{ negative: periodDiff > 0, positive: periodDiff < 0 }">
              {{ periodDiff >= 0 ? '+' : '' }}{{ formatAmount(Math.abs(periodDiff)) }}
            </div>
              </div>
          <div class="stat-card">
            <div class="label">收支结余(元)</div>
            <div class="value" :class="{ negative: overview.balance < 0, positive: overview.balance > 0 }">
              {{ formatAmount(overview.balance) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 趋势图 -->
      <div class="chart-section">
        <div class="section-title">
          <span>{{ activeType === 'expense' ? '支出' : '收入' }}趋势</span>
        </div>
        <div class="chart-container" v-if="dailyStats.length > 0">
          <Line :data="lineChartData" :options="lineChartOptions" />
                </div>
        <div v-else class="empty-chart">
          <van-empty description="暂无数据" />
                </div>
              </div>

      <!-- 分类饼图 -->
      <div class="chart-section">
        <div class="section-title">
          <span>分类概况</span>
        </div>
        <div class="pie-container" v-if="currentCategoryStats.length > 0">
          <div class="pie-chart">
            <Doughnut :data="pieChartData" :options="pieChartOptions" />
            <div class="pie-center-text">
              <div class="total-amount">¥{{ formatAmount(currentTotal) }}</div>
              <div class="total-label">总{{ activeType === 'expense' ? '支出' : '收入' }}</div>
            </div>
          </div>
        </div>
        <div v-else class="empty-chart">
          <van-empty description="暂无数据" />
            </div>
          </div>

      <!-- 分类排行榜 -->
      <div class="ranking-section">
        <div class="section-title">
          <span>分类明细</span>
        </div>
        <div 
          v-for="(item, index) in currentCategoryStats.slice(0, 10)" 
                :key="item.categoryId"
          class="ranking-item"
          @click="goToCategoryDetail(item)"
              >
          <div class="rank-number">{{ index + 1 }}</div>
          <div class="category-icon-wrapper" :style="{ backgroundColor: item.categoryColor + '20' }">
            <span class="category-icon" :style="{ color: item.categoryColor }">
                    {{ CATEGORY_ICONS[item.categoryIcon as keyof typeof CATEGORY_ICONS] || CATEGORY_ICONS.default }}
                  </span>
                </div>
                <div class="category-info">
                  <div class="category-name">{{ item.categoryName }}</div>
                  <div class="category-count">{{ item.count }}笔</div>
                </div>
                <div class="category-amount">
            <div class="amount">¥{{ formatAmount(item.totalAmount) }}</div>
            <div class="percentage">{{ ((item.totalAmount / currentTotal) * 100).toFixed(1) }}%</div>
                </div>
          <van-icon name="arrow" class="arrow-icon" />
              </div>
        
        <div v-if="currentCategoryStats.length === 0" class="empty-state">
          <van-empty description="暂无数据" />
            </div>
          </div>
        </div>

    <!-- 自定义日期选择弹窗 -->
    <van-popup v-model:show="showCustomDatePicker" position="bottom" round closeable>
      <div class="custom-date-popup">
        <van-nav-bar title="自定义时间" />
        
        <!-- 快捷选择 -->
        <div class="quick-select">
          <div class="quick-label">快捷选择</div>
          <div class="quick-buttons">
            <van-button size="small" plain @click="quickSelectDate('all')">全部</van-button>
            <van-button size="small" plain @click="quickSelectDate('year')">近一年</van-button>
            <van-button size="small" plain @click="quickSelectDate('month')">近30天</van-button>
            <van-button size="small" plain @click="quickSelectDate('week')">近7天</van-button>
          </div>
        </div>
        
        <!-- 自定义日期 -->
        <div class="date-range-select">
          <div class="date-label">自定义</div>
          <van-cell-group>
            <van-cell
              title="开始日期"
              :value="customStartDate"
              is-link
              @click="showStartDatePicker = true"
            />
            <van-cell
              title="结束日期"
              :value="customEndDate"
              is-link
              @click="showEndDatePicker = true"
            />
          </van-cell-group>
        </div>

        <!-- 确认按钮 -->
        <div class="confirm-button">
          <van-button type="primary" block round @click="confirmCustomDate">
            确定
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 开始日期选择器 -->
    <van-popup v-model:show="showStartDatePicker" position="bottom">
      <van-date-picker
        v-model="customStartDate"
        title="选择开始日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date()"
        @confirm="onStartDateConfirm"
        @cancel="showStartDatePicker = false"
      />
    </van-popup>

    <!-- 结束日期选择器 -->
    <van-popup v-model:show="showEndDatePicker" position="bottom">
      <van-date-picker
        v-model="customEndDate"
        title="选择结束日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date()"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<style scoped>
.statistics-view {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.report-tabs {
  display: flex;
  justify-content: space-around;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.report-tabs .tab-item {
  padding: 6px 20px;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  color: #666;
}

.report-tabs .tab-item.active {
  background: #1989fa;
  color: #fff;
}

.time-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: #fff;
  gap: 20px;
}

.time-selector .van-icon {
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  color: #333;
}

.time-selector .van-icon.disabled {
  opacity: 0.3;
  pointer-events: none;
}

.time-text {
  font-size: 16px;
  font-weight: 500;
  min-width: 120px;
  text-align: center;
}

.type-tabs {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 16px;
  background: #fff;
}

.type-tabs .tab-item {
  padding: 8px 32px;
  border-radius: 20px;
  background: #f5f5f5;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 15px;
}

.type-tabs .tab-item.active {
  background: #1989fa;
  color: #fff;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.content {
  padding: 12px 16px;
}

.stats-cards {
  margin-bottom: 12px;
}

.card-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.stat-card .label {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.stat-card .value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-card .value.primary {
  color: #1989fa;
  font-size: 24px;
}

.stat-card .value.negative {
  color: #ff4444;
}

.stat-card .value.positive {
  color: #07c160;
}

.chart-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.chart-container {
  height: 220px;
  position: relative;
}

.pie-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.pie-chart {
  width: 280px;
  height: 280px;
  position: relative;
}

.pie-center-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  pointer-events: none;
}

.total-amount {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.total-label {
  font-size: 13px;
  color: #999;
}

.empty-chart {
  padding: 40px 0;
}

.ranking-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background 0.2s;
}

.ranking-item:active {
  background: #fafafa;
}

.ranking-item:last-child {
  border-bottom: none;
}

.rank-number {
  width: 24px;
  font-size: 16px;
  font-weight: bold;
  color: #999;
  margin-right: 12px;
}

.category-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.category-icon {
  font-size: 20px;
}

.category-info {
  flex: 1;
}

.category-name {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.category-count {
  font-size: 12px;
  color: #999;
}

.category-amount {
  text-align: right;
  margin-right: 8px;
}

.category-amount .amount {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.category-amount .percentage {
  font-size: 12px;
  color: #999;
}

.arrow-icon {
  color: #c8c9cc;
  font-size: 16px;
}

.empty-state {
  padding: 40px 0;
}

/* 自定义日期选择弹窗 */
.custom-date-popup {
  padding-bottom: 20px;
}

.quick-select {
  padding: 20px 16px;
}

.quick-label {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.quick-buttons {
  display: flex;
  gap: 10px;
}

.quick-buttons .van-button {
  flex: 1;
}

.date-range-select {
  padding: 0 16px 20px;
}

.date-label {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.confirm-button {
  padding: 0 16px;
}
</style>
